package gwt.coonay.server;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.mortbay.log.Log;

import gwt.common.SpringUtil;
import gwt.coonay.client.NoteDTO;
import gwt.coonay.client.NotePack;
import gwt.coonay.client.NoteService;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
@SuppressWarnings("serial")
public class NoteServiceImpl extends RemoteServiceServlet implements NoteService {
	
	static Logger log = Logger.getLogger(NoteServiceImpl.class);
	public NotePack updateAgent(){
		log.info("Trace into...");
		NotePack np = new NotePack();
		UserService userService = UserServiceFactory.getUserService();
		HttpServletRequest  request = getThreadLocalRequest();
		User user = userService.getCurrentUser();
		Principal p = request.getUserPrincipal();
		
		if ( p != null ){
			log.info("user has logined in");
			np.setCurrentUser(user.getNickname());
			np.setGmail(user.getEmail());
			//direct to homepage when logout
			np.setSignUrl(userService.createLogoutURL("/"));
		}
		else{
			//direct to homepage when login
			np.setSignUrl(userService.createLoginURL("/"));
		}
		
		JpaNoteDao jnd = (JpaNoteDao)SpringUtil.getBean("noteDao");
		List<Note> notesStream = (List<Note>)jnd.loadAll();
		
		List<NoteDTO> notes = jnd.streamResult(notesStream);
		np.setNotes(notes);		
		//setNotes(np);
				
		return np;
	}
	
	private void setNotes(NotePack np){
		NoteDTO n = new NoteDTO();
		
		List<NoteDTO> notes = new ArrayList<NoteDTO>();
		n.setGmail("t@163.com");		
		notes.add(n);
		np.setNotes(notes);	
	}
}
